<template>
  <div class="h-3/4 border rounded-10px">
    <div class="flex">
      <div class="mr-10px" @click="clickCard(app)" v-for="app in appCardList" :key="app.appId">
        <Card
          class="shadow-lg cursor-pointer sl-app-card"
          :bordered="true"
          style="cursor: poniter; height: 190px; min-width: 315px; width: 315px; border-radius: 10px; padding: 0px"
        >
          <img class="w-full h-140px" :src="app.logo" />
          <div class="font-light text-center text-18px mt-15px">{{ app.name }}</div>
        </Card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Card } from 'ant-design-vue';
import { useUserStoreWithout } from '/@/store/modules/user';
import { chooseApp, getAllApp } from '/@/api/sys/user';
import { ref } from 'vue';
import { transformEnvToDev } from '/@/utils/helper/envTransfrom';

const userStore = useUserStoreWithout();
const appCardList = ref([]);
const tenantCode = userStore.getUserInfo?.tenantCode as string;
const userId = userStore.getUserInfo?.userId as string;
const sessionId = userStore.getUserInfo?.sessionId as string;
const consoleDomain = userStore.getUserInfo?.consoleDomain as string;

const getAppList = async () => {
  try {
    const appList = await getAllApp({
      userId,
      tenantCode,
    });
    appList.items.forEach((e) => {
      e.logoPath = new URL(`../../../../../assets/svg/${e.logo}.svg`, import.meta.url).href;
    });
    appCardList.value = appList.items;
  } catch (error) {
    // eslint-disable-next-line no-console
    console.log(error);
    throw error;
  }
};

getAppList();

async function clickCard(app) {
  const appId = app.appId;
  try {
    const redirectUrl = await chooseApp({
      tenantCode,
      appId,
      userId,
      sessionId,
    });
    // use to deliver console app token
    const redirectUrlWithlocalToken = `${redirectUrl}&consoleDomain=${consoleDomain}&sessionId=${sessionId}`;
    transformEnvToDev(redirectUrlWithlocalToken, 3200, 'hotel');
  } catch (error) {
    // 未认证时强制登出
    if (error.message === '未认证') {
      userStore.logout(true);
    }
  }
}
</script>

<style lang="less">
.sl-app-card {
  .ant-card-body {
    padding: 0;
  }
}
</style>
